package com.simple.quotes.gui;

import com.simple.quotes.core.Quote;
import com.simple.quotes.loading.QuoteLoader;
import com.simple.quotes.loading.QuoteLoadingException;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;

/**
 * @author Petro
 */
public class LoadFileAction extends AbstractAction {
    private JFileChooser chooser = new JFileChooser();
    private MainFrame frame;

    public LoadFileAction(MainFrame frame) {
        this.frame = frame;
        putValue(Action.NAME, "Load");
        putValue(Action.SHORT_DESCRIPTION, "Load data from file");
        putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl O"));
        putValue(Action.MNEMONIC_KEY, new Integer('L'));
    }

    public void actionPerformed(ActionEvent event) {
        chooser.setCurrentDirectory(new File("."));
        int result = chooser.showOpenDialog(frame);
        switch (result) {
            case JFileChooser.ERROR_OPTION:
                frame.setStatus("Error opening file!");
                break;
            case JFileChooser.APPROVE_OPTION:
                try {
                    QuoteLoader.load(chooser.getSelectedFile());
                } catch (QuoteLoadingException e) {
                    frame.setStatus(e.getMessage());
                }
                frame.getTextArea().setText("");
                for (Quote quote : QuoteLoader.getList())
                    frame.getTextArea().append(quote.toString());
        }
    }
}
